package com.mohe.dangjian.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录过滤器
 * 
 * @author wxm
 * 
 */
public class LoginFilter implements Filter {

	// 忽略过滤的链接
	private Set<String> jspSet = null;

	public void init(FilterConfig config) throws ServletException {
		jspSet = new HashSet<String>();
		jspSet.add("/");
		jspSet.add("/login.jsp");
	}

	@Override
	public void destroy() {
		jspSet.clear();
		jspSet = null;
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession(true);

		// 请求连接
		StringBuffer url = request.getRequestURL();
		int index = url.lastIndexOf("/");
		String before = url.substring(0, index);
		String jsp = url.substring(index);

		// 登录用户
		Long adminKey = (Long) session.getAttribute("adminKey");
		if (adminKey == null) {

			// 判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
			if (!jspSet.contains(jsp)) {

				// 将未完成的连接存放
				session.setAttribute("url", url.toString());
				response.sendRedirect(before + "/login.jsp");
				return;
			}
		}

		arg2.doFilter(arg0, arg1);
	}

}